import './polyfill'
import Map from './Map.js'

export default class Looker {
    static child = new Looker()
    static single() { return Looker.child }
    constructor() {
        this.funcMap = new Map()
        this.hashFuncMap = new Map()
    }
    props = new Map()
    listen = (key, func, isOnly = false) => {
        let funcs = []
        if (this.funcMap.get(key)) {
            funcs = this.funcMap.get(key)
        }
        funcs.push(func)
        this.funcMap.set(key, funcs)

        let hashMap = new Map()
        let hashString = ''
        let hash = hashString.random(20)
        if (this.hashFuncMap.get(key)) {
            hashMap = this.hashFuncMap.get(key)
        }
        hashMap.set(hash, funcs.length - 1)
        this.hashFuncMap.set(key, hashMap)
        return hash
    }
    trigger = (key, value, hash = null) => {
        if (hash == null) {
            let funcs = new Map()
            if (this.funcMap.get(key)) {
                funcs = this.funcMap.get(key)
            }
            for (let i in funcs) {
                if (funcs[i]) funcs[i](value)
            }
        } else {
            let funcs = new Map()
            if (this.funcMap.get(key)) {
                funcs = this.funcMap.get(key)
            }
            let hashMap = new Map()
            if (this.hashFuncMap.get(key)) {
                hashMap = this.hashFuncMap.get(key)
            }
            let i = hashMap.get(hash)
            funcs[i](value)
        }
    }
    removeAll = (key) => {
        this.funcMap.set(key, [])
        this.funcMap.delete(key)
    }
    removeHash = (key, hash) => {
        let funcs = new Map()
        if (this.funcMap.get(key)) {
            funcs = this.funcMap.get(key)
        }
        let hashMap = new Map()
        if (this.hashFuncMap.get(key)) {
            hashMap = this.hashFuncMap.get(key)
        }
        let i = hashMap.get(hash)
        delete funcs[i]
        this.funcMap.set(key, funcs)
    }
}